<template>
  <view class="upload">
    <!-- 预览 -->
    <view v-if="viewType == 'upload'" class="upload-fileList">
      
      <view 
		:class="{'filelist-item':true,file:item.type == 'file' ? true : false}"
        v-for="(item, i) of fileList"
        :key="i"
        @click="preImage(item, i)"
      >
        <!-- 预览logo --> 
        <image v-if="item.type == 'image'" :src="/^http/.test(item.url) ?    item.url : config.fileUrl + item.url  || item.path" mode="aspectFill" />
		<view  v-else  class="upload-file">
			<image  src="../../static/file.png" mode="aspectFill" />
		</view>
        <!-- 删除选择 -->
        <view v-if="!disabled" class="close-wrapper iconfont icon-close"  @click.stop="rmImage(i)"> </view>
      </view>
	  <!-- 默认添加 -->
	  <view v-if="!disabled && maxSelect > fileList.length" class="filelist-item" @click="dialog = true">
	    <text class="iconfont icon-add" style="#ccc" />
	  </view> 
    </view>
	
	 <view v-if="viewType == 'download'" class="download-fileList">
		<view
		 class="download-item "
		  v-for="(item, i) of fileList"
		  :key="i" 
		>
		<text class="flex-text-ellipsis" style="flex:1">{{item.name}}</text>
		</view> 
	 </view>
    <!-- 选择预览类型 -->
    <u-popup
      :show="dialog"
      :round="15"
      mode="bottom"
      :customStyle="{ overflow: 'hidden' }"
      @close="dialog = false"
    >
      <view class="dialog-content">
        <view class="option-li">
          <u-button
            type="primary"
            text="微信文件"
            @click="chooseFile('file')"
          ></u-button>
        </view>
        <view class="option-li">
          <u-button
            type="primary"
            text="本地图库"
            @click="chooseFile('image')"
          ></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import config from '@/config.js'
import { upFile} from '@/utils/request.js'
export default {
  name: 'upload',
  props: {
	viewType:{
		type:  String,
		default: 'upload'
	},
    maxSelect: {
      type: Number | String,
      default: 1
    },
	async: {
      type: Boolean,
      default: false
    },
    init: {
     type: Array,
    },
	disabled:{
		type: Boolean,
		default: false
	}
  },
  computed: {
    count() {
      return this.maxSelect > this.fileList.length
        ? this.maxSelect - this.fileList.length
        : 1
    }, 
  },
  watch:{
	init:{
		handler(newV,val){
			console.log('upload init watch',newV,val)
			if (newV) {
				this.fileListInit()
			  }
		} ,
		immediate:true
	}
  },
  data() {
    return {
		config,
      dialog: false,
      fileList: []
    }
  },
  // created() {
  //   if (this.init) {
  //     this.fileListInit()
  //   }
  // },
  methods: {
	getFormatFile(){
		// console.log('getFormatFile',this.fileList)
		let datas = this.fileList.map(item=> item.data)
		return  encodeURI(JSON.stringify(datas)) 
	},
	fileListInit() {
		// console.log('init',this.init)
	  this.init.forEach(item =>{
		 let img = /\.(jpeg|png|jpg|gif)$/.test(item.name) 
		 this.fileList.push({
			 ...item,
			 data : item,
			 upload :true ,
			 type: img ? 'image' : 'file'
		 })
	  })
	  // this.fileList = this.init
	  // console.log('init update ',this.getFormatFile())
	  this.$emit('change', this.getFormatFile())
	  
	},
    chooseFile(type) {
	let self = this
      let method = 'chooseFile'
      if (type == 'file') {
        method = 'chooseMessageFile'
      } else if (type == 'image') {
        method = 'chooseImage'
      }
	  console.log('choose:', type,method,self.count)
      //创建文件流
      uni[method]({
        count: self.count,
        success:  async function(res) {
          console.log('选择的文件：',res);
          if (res.errMsg.indexOf('ok') >= 0) {
			  for(const item of res.tempFiles){ 
				 let file = {
					 type,
					 name:item.name || item.path,
					 path:item.path,
					 url:'',
					 upload:false
				 }
				 if(!self.async){
				 await self.uploadFile(file).then(res=>{
					 file.url =   res.url ;
					 file.upload = true
					 file.data = res
					 self.fileList.push(file)
				 }) 
				 }
				  console.log('file=:',file)
			 }
			 console.log('fileList:',self.getFormatFile())
			  self.$emit('change',self.getFormatFile())
          }
		  self.dialog = false
        },
        fail(err) {
			self.dialog = false
          console.log('文件选择失败',err);
        }
      })
    },
    uploadFile(file) {
		let self = this
     return new Promise(async(resolve,reject)=>{
		await upFile(file.path).then(res=>{ 
			 console.log('上传成功:',file.name)
			 resolve(res)
		 }).catch(err=>{
			 console.log('上传失败:',file.name)
			 self.$store.dispatch('configs/syncSetConfigs',{
				  toast:true,
				  toastText:'图片上传失败或太大，请稍后再试'
			}) 
			 reject(false)
		 })
	 })
    },  

    rmImage(i) {
      this.fileList.splice(i, 1) 
	  this.$emit('change',this.getFormatFile())
    },
    preImage(item) {
		let that = this
	  if(!/\.(jpeg|png|jpg|gif)$/.test(item.name)){
		  return that.$store.dispatch('configs/syncSetConfigs', {
           toast:true,
           toastText:'该文件类型不支持预览！'
          })
	  }
      let images = this.fileList.filter(f=> f.type == 'image').map((m) => m.url)
      let imageUrls = images.map((m) => m.url)
      let imageIndex = images.findIndex((i) => i.name == item.name)
      uni.previewImage({
        current: imageIndex || 0,
        urls: images,
        success() {},
        fail() {
          that.$store.dispatch('configs/syncSetConfigs', {
           toast:true,
           toastText:'图片上传失败，请稍后再试'
          })
        }
      })
    }, 
	clear(){
		this.fileList = []
	},
	testUpload(){
		return this.fileList.every(e=>e.upload)
	}
  }
}
</script>

<style lang="scss" scoped>
.upload {
  padding: 10rpx 0;
}
.filelist-item {
  position: relative;
  width: 150rpx;
  height: 150rpx;
  margin: 10rpx;
  display: grid;
  place-items: center;
  font-size: 80rpx;
  border: 1rpx solid #ccc;
  border-radius: 15rpx;
  overflow: hidden;
  &.file{
	  background-color: #fff;
  }
}
.upload-fileList {
  display: flex;
  flex-wrap: wrap;
  color: #26bbf5;
  font-size: 32rpx;
 

  & .close-wrapper {
    position: absolute;
    top: 0rpx;
    right: 0rpx;
    width: 40rpx;
    height: 40rpx;  
    text-align: center;
    line-height: 40rpx; 
    font-size:40rpx;
	color: #fff;
  }
}
.option-li {
  padding: 20rpx 40rpx;
}
.upload-file{ 
	width: 120rpx;
	height:120rpx; 
}
.download-fileList{
	    color: #26bbf5;
	    font-size: 32rpx;
		.download-item{
			display: flex;
			width: 100%;
		}
}
</style>
